package com.party.admin.web.controller.mall;

import com.google.common.collect.Maps;
import com.party.admin.biz.file.FileBizService;
import com.party.admin.biz.mall.MallStoreBizService;
import com.party.admin.web.dto.AjaxResult;
import com.party.admin.web.dto.input.mall.MallStoreInput;
import com.party.common.utils.StringUtils;
import com.party.core.model.mall.MallStoreOutput;
import com.party.core.model.member.MemberGroup;
import com.party.core.service.mall.biz.StoreResourceBizService;
import com.party.core.service.member.IMemberGroupService;
import com.party.core.service.cos.CosBizService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import java.util.List;
import java.util.Map;

/**
 * 商城店铺控制器
 * Created by yifeng
 *
 * @date 2018/4/3 0003
 * @time 上午 10:45
 */
@Controller
@RequestMapping("mall/store")
public class MallStoreController {

    @Value("#{party['shop.url.protocol']}")
    private String shopUrl;

    @Autowired
    private CosBizService cosBizService;
    @Autowired
    private MallStoreBizService mallStoreBizService;
    @Autowired
    private StoreResourceBizService storeResourceBizService;
    @Autowired
    private IMemberGroupService memberGroupService;
    @Autowired
    private FileBizService fileBizService;

    Logger logger = LoggerFactory.getLogger(getClass());

    @RequestMapping("storeForm")
    public ModelAndView storeForm() {
        ModelAndView mv = new ModelAndView("/mall/store/storeForm");
        MallStoreOutput mallStoreOutput = mallStoreBizService.getStoreView();
        mv.addObject("mallStore", mallStoreOutput);

        try {
            Map<String, String> qrCodeMap = Maps.newHashMap();
            if (StringUtils.isNotEmpty(mallStoreOutput.getId())) {
                String memberId = mallStoreOutput.getCreateBy();
                if (StringUtils.isEmpty(memberId)) {
                    MemberGroup txz = memberGroupService.getTXZ();
                    memberId = txz.getId();
                }
                String filePath = fileBizService.getUploadCIPath(memberId, "shop");
                String fileName = "home_" + mallStoreOutput.getId();
                String content = shopUrl + "home?storeId=" + mallStoreOutput.getId();
                String qrCodeUrl = cosBizService.getPreviewPictureUrl(filePath + fileName);
                qrCodeMap.put("qrCode", qrCodeUrl);
                qrCodeMap.put("qrCodeContent", content);
            }
            mv.addObject("qrCodeMap", qrCodeMap);
        } catch (Exception e) {
            logger.error("获取店铺主页二维码异常", e);
        }

        return mv;
    }

    @ResponseBody
    @RequestMapping("getStoreResource")
    public AjaxResult getStoreResource(String storeId) {
        if (StringUtils.isEmpty(storeId)) {
            return AjaxResult.error("店铺id不能为空");
        }
        try {
            MallStoreOutput mallStoreOutput = storeResourceBizService.getStoreResource(storeId);
            return AjaxResult.success(mallStoreOutput);
        } catch (Exception e) {
            logger.error("加载店铺资源异常", e);
            return AjaxResult.error("加载店铺资源异常");
        }
    }

    /**
     * 保存
     *
     * @param mallStoreInput 输入参数
     * @return
     */
    @ResponseBody
    @RequestMapping("save")
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public AjaxResult save(MallStoreInput mallStoreInput, BindingResult result) {
        try {
            // 数据验证
            if (result.hasErrors()) {
                List<ObjectError> allErros = result.getAllErrors();
                return AjaxResult.error(allErros.get(0).getDefaultMessage());
            }
            mallStoreBizService.saveStoreBiz(mallStoreInput);
            return AjaxResult.success();
        } catch (Exception e) {
            logger.error("保存店铺异常", e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return AjaxResult.error("保存店铺失败");
        }
    }
}
